package com.pdformparent;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.dengpp.pdform.AttributeFormActivity;
import com.dengpp.pdform.config.AttributeConfig;
import com.dengpp.pdform.config.FormConfig;
import com.dengpp.pdform.model.CascadingOption;
import com.dengpp.pdform.model.MediaFile;
import com.dengpp.pdform.model.MediaFileDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_ATTRIBUTE_FORM = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 注册自定义视图类
        AttributeFormActivity.registerCustomView("custom_input", SimpleInputView.class);
        AttributeFormActivity.registerCustomView("complex_custom", XmlBasedCustomView.class);
        AttributeFormActivity.registerCustomView("conditional_input", RadioWithInputView.class);
        AttributeFormActivity.registerCustomView("check", CheckboxGroupView.class);

        findViewById(R.id.btn_open_form).setOnClickListener(v -> openAttributeForm());
    }

    private void openAttributeForm() {
        // 创建表单配置
        List<AttributeConfig> attributes = new ArrayList<>();

        /**
         * 验证规则使用示例
         */
        // 数字输入框示例
        attributes.add(new AttributeConfig("age", "年龄", AttributeConfig.AttributeType.NUMBER)
                .setRequired(true)
                .setValidationRule("positive_integer")
                .setMinValue(0)
                .setMaxValue(150)
                .setIshide(true)
                .setValue(66)
                .setValidationMessage("年龄必须是0-150之间的整数"));

        attributes.add(new AttributeConfig("salary", "月薪", AttributeConfig.AttributeType.NUMBER)
                .setValidationRule("positive_decimal")
                .setMinValue(0)
                .setIshide(true)
                .setValidationMessage("月薪必须为正数"));

        // 带验证的文本输入框
        attributes.add(new AttributeConfig("phone", "手机号", AttributeConfig.AttributeType.TEXT)
                .setRequired(true)
                .setValue("13333333333")
                .setIshide(true)
                .setValidationRule("phone")
                .setValidationMessage("请输入正确的手机号码")
                .setMaxLength(11));

        attributes.add(new AttributeConfig("email", "邮箱", AttributeConfig.AttributeType.TEXT)
                .setValidationRule("email")
                .setValidationMessage("请输入正确的邮箱地址"));

        attributes.add(new AttributeConfig("id_card", "身份证", AttributeConfig.AttributeType.TEXT)
                .setValidationRule("id_card")
                .setValidationMessage("请输入正确的身份证号码")
                .setMaxLength(18));

        // 普通文本输入框
        attributes.add(new AttributeConfig("name1", "姓名", AttributeConfig.AttributeType.TEXT)
                .setRequired(true)
                .setValue("dbegpp")
                .setMaxLength(20));

        // 自定义正则验证
        attributes.add(new AttributeConfig("custom_field", "自定义字段", AttributeConfig.AttributeType.TEXT)
                .setValidationRule("[A-Z]{3}-\\d{4}")
                .setValidationMessage("格式应为：ABC-1234"));

        // 文本输入
        attributes.add(new AttributeConfig("height", "身高", AttributeConfig.AttributeType.TEXT)
                .setRequired(true)
                .setValue(66)
                .setHint("请输入姓名"));

        // 多行文本
        attributes.add(new AttributeConfig("description", "描述", AttributeConfig.AttributeType.MULTI_LINE_TEXT)
                .setMaxLines(3)
                .setHint("请输入描述信息"));

        // 单选
        List<String> genders = Arrays.asList("男", "女", "其他");
        attributes.add(new AttributeConfig("gender", "性别", AttributeConfig.AttributeType.RADIO)
                .setValue("男")
                .setOptions(genders));


        // 多选
        List<String> hobbies = Arrays.asList("阅读1", "运动1", "音乐1", "旅行1", "运动2", "音乐2", "旅行2", "运动3", "音乐3", "旅行3", "运动4", "音乐4", "旅行4");
        attributes.add(new AttributeConfig("hobbies", "兴趣爱好", AttributeConfig.AttributeType.CHECKBOX)
                .setOptions(hobbies));


        // 日期
        attributes.add(new AttributeConfig("birthday", "出生日期", AttributeConfig.AttributeType.DATE)
                .setValue("1990-01-01")
                .setDateFormat("yyyy-MM-dd"));

        // 下拉选择
        List<String> cities = Arrays.asList("北京", "上海", "广州", "深圳");
        attributes.add(new AttributeConfig("city", "城市", AttributeConfig.AttributeType.DROPDOWN)
                .setValue("北京")
                .setOptions(cities));


        // 媒体文件
        MediaFileDialog mediaFileDialog = new MediaFileDialog();
        mediaFileDialog.setTitle("拍照录屏");
        mediaFileDialog.setItems(new String[]{"相册选择", "拍照", "录屏"});
        mediaFileDialog.setCurrentAction(new String[]{"gallery", "camerax", "video"});

        List<MediaFile> mediaFiles = new ArrayList<>();

        mediaFiles.add(new MediaFile("file:///storage/emulated/0/Android/data/com.pdformparent/files/Pictures/IMG_20251118_121225.jpg", MediaFile.MediaType.IMAGE));
        mediaFiles.add(new MediaFile("content://media/external/images/media/1023225", MediaFile.MediaType.IMAGE));

        attributes.add(new AttributeConfig("media", "媒体文件", AttributeConfig.AttributeType.MEDIA)
                .setValue(mediaFiles)//设置值
                .setMediaSpanCount(1)//设置网格数，默认3列
                .setMediaFileDialog(mediaFileDialog));//多媒体按钮点击内容


        //测试第二个多媒体
        attributes.add(new AttributeConfig("media111", "媒体文件111", AttributeConfig.AttributeType.MEDIA));


        // 创建多级下拉数据
        List<CascadingOption> cascadingOptions = new ArrayList<>();

        // 第一级：省份
        CascadingOption beijing = new CascadingOption("beijing", "北京市");
        CascadingOption jiangsu = new CascadingOption("jiangsu", "江苏省");
        CascadingOption zhejiang = new CascadingOption("zhejiang", "浙江省");

        // 第二级：城市
        List<CascadingOption> beijingCities = new ArrayList<>();
        beijingCities.add(new CascadingOption("beijing_city", "北京市"));
        beijing.setChildren(beijingCities);

        List<CascadingOption> jiangsuCities = new ArrayList<>();
        jiangsuCities.add(new CascadingOption("nanjing", "南京市"));
        jiangsuCities.add(new CascadingOption("suzhou", "苏州市"));
        jiangsuCities.add(new CascadingOption("wuxi", "无锡市"));
        jiangsu.setChildren(jiangsuCities);

        List<CascadingOption> zhejiangCities = new ArrayList<>();
        zhejiangCities.add(new CascadingOption("hangzhou", "杭州市"));
        zhejiangCities.add(new CascadingOption("ningbo", "宁波市"));
        zhejiangCities.add(new CascadingOption("wenzhou", "温州市"));
        zhejiang.setChildren(zhejiangCities);

        // 第三级：区县
        List<CascadingOption> nanjingDistricts = new ArrayList<>();
        nanjingDistricts.add(new CascadingOption("xuanwu", "玄武区"));
        nanjingDistricts.add(new CascadingOption("gulou", "鼓楼区"));
        nanjingDistricts.add(new CascadingOption("qinhuai", "秦淮区"));

        // 找到南京选项并设置区县
        for (CascadingOption city : jiangsuCities) {
            if ("nanjing".equals(city.getValue())) {
                city.setChildren(nanjingDistricts);
                break;
            }
        }

        cascadingOptions.add(beijing);
        cascadingOptions.add(jiangsu);
        cascadingOptions.add(zhejiang);

        List<String> defaultSelected = new ArrayList<>();
        defaultSelected.add("beijing");

        // 创建多级下拉表单项
        attributes.add(new AttributeConfig("address", "地址选择", AttributeConfig.AttributeType.CASCADING_DROPDOWN)
                .setRequired(true)
                .setValue(defaultSelected)
                .setCascadingOptions(cascadingOptions)
                .setSelectedCascadingValues(defaultSelected)); // 设置默认选中


        /**
         * 自定义视图使用----------------------------------------------------
         */
        // 1. 简单输入框自定义视图
        attributes.add(new AttributeConfig("simple_input", "简单输入框",
                AttributeConfig.AttributeType.CUSTOM_VIEW)
                .setCustomViewClass(SimpleInputView.class)
                .setValue("默认值"));

        // 2. 多选框组自定义视图
        List<String> checkboxOptions = Arrays.asList("选项A", "选项B", "选项C", "选项D");
        attributes.add(new AttributeConfig("checkbox_group", "多选组",
                AttributeConfig.AttributeType.CUSTOM_VIEW)
                .setCustomViewClass(CheckboxGroupView.class)
                .setOptions(checkboxOptions)
                .setValue(Arrays.asList("选项A", "选项C")));

        // 3. 基于 XML 的复杂自定义视图
        Map<String, Object> complexValue = new HashMap<>();
        complexValue.put("input1", "值1");
        complexValue.put("input2", "值2");
        complexValue.put("option1", true);
        complexValue.put("option2", false);

        attributes.add(new AttributeConfig("complex_view", "复杂视图",
                AttributeConfig.AttributeType.CUSTOM_VIEW)
                .setCustomViewClass(XmlBasedCustomView.class)
                .setValue(complexValue));

        // 4. 单选控制输入框显示
        attributes.add(new AttributeConfig("radio_with_input", "选项控制显示",
                AttributeConfig.AttributeType.CUSTOM_VIEW)
                .setCustomViewClass(RadioWithInputView.class)
                .setValue(new HashMap<String, Object>() {{
                    put("selectedOption", "option1");
                }}));
        /**
         * 自定义视图使用----------------------------------------------------
         */


        // 创建表单配置
        FormConfig formConfig = new FormConfig("用户信息编辑", attributes)
                .setSubmitButtonText("确认修改")
                .setCancelButtonText("放弃修改");

        // 启动表单
        AttributeFormActivity.start(this, formConfig, REQUEST_ATTRIBUTE_FORM);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ATTRIBUTE_FORM) {
            if (resultCode == RESULT_OK && data != null) {
                // 处理表单提交结果
                @SuppressWarnings("unchecked")
                HashMap<String, Object> formData = (HashMap<String, Object>)
                        data.getSerializableExtra("form_data");

                // 使用表单数据
                for (Map.Entry<String, Object> entry : formData.entrySet()) {
                    Log.d("FormData", entry.getKey() + ": " + entry.getValue());
                }

                Toast.makeText(this, "表单提交成功", Toast.LENGTH_SHORT).show();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "表单已取消", Toast.LENGTH_SHORT).show();
            }
        }
    }

}